﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Ellanet
{
    public partial class AddHosts : Form
    {
        public string[] Hosts { get; private set; }

        public AddHosts()
        {
            InitializeComponent();
            hostsTextBox.TextChanged += hostsTextBox_TextChanged;
            addButton.Click += addButton_Click;
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            var hosts = new List<string>();
            string hostString = hostsTextBox.Text.Trim();

            if (hostString.Contains("\r"))
            {
                hostString = hostString.Replace("\r", " ");
            }

            if (hostString.Contains("\t"))
            {
                hostString = hostString.Replace("\t", " ");
            }

            if (hostString.Contains("\n"))
            {
                hostString = hostString.Replace("\n", " ");
            }

            if (hostString.Contains(","))
            {
                hostString = hostString.Replace(",", " ");
            }

            foreach (string host in hostString.Split(Convert.ToChar(" ")))
            {
                if (!String.IsNullOrEmpty(host) && !hosts.Contains(host.Trim(), StringComparer.CurrentCultureIgnoreCase))
                {
                    hosts.Add(host.Trim());
                }
            }

            Hosts = hosts.ToArray();
            DialogResult = DialogResult.OK;
            Close();
        }

        private void hostsTextBox_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(hostsTextBox.Text) && (hostsTextBox.Text.Trim().Length > 0))
            {
                addButton.Enabled = true;
            }
            else
            {
                addButton.Enabled = false;
            }
        }
    }
}
